//
//  HReducer.m
//  TestOCRedux
//
//  Created by Hotacool on 2019/1/18.
//  Copyright © 2019 Hotacool. All rights reserved.
//

#import "HReducer.h"

HReducer combineReducers(NSDictionary <NSString*, HReducer>*dic) {
    NSCAssert(dic != nil && dic.count > 0, @"reducers dic must has value");
    HReducer reducer = ^id<HStateType>(id<HActionType> action, id<HStateType> state){
        if (!state) {
            state = [HState new];
        } else {
            state = [((HState*)state) copy];
        }
        [dic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, HReducer  _Nonnull rds, BOOL * _Nonnull stop) {
            id<HStateType> t = rds(action, state[key]);
            if (t) {
                state[key] = t;
            }
        }];
        return state;
    };
    return reducer;
}

HReducer appReducer(NSArray <HReducer>*arr, NSString* stateClassName) {
    NSCAssert(arr != nil && arr.count > 0, @"reducers array must has value");
    HReducer reducer = ^id<HStateType>(id<HActionType> action, id<HStateType> state){
        Class cls = NSClassFromString(stateClassName);
        if (!state) {
            if (cls) {
                state = [cls new];
            } else {
                state = [HState new];
            }
        } else {
            state = [((HState*)state) copy];
        }
        HState __block* tmpState = state;
        [arr enumerateObjectsUsingBlock:^(HReducer  _Nonnull rds, NSUInteger idx, BOOL * _Nonnull stop) {
            id<HStateType> t = rds(action, tmpState);
            if (t) {
                tmpState = rds(action, tmpState);
            }
        }];
        return tmpState;
    };
    return reducer;
}
